import RichTextEditor from '@/components/RichTextEditor';
import { uploadMinio } from '@/services/common';
import {
  addProductInfo,
  deleteProductInfo,
  qryMainCategoryList,
  qryProductInfoDetail,
  qryProductListPage,
  updateProductInfo,
} from '@/services/product';
import { qryMainCategoryDetail } from '@/services/productCategory';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import {
  Button,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  Popconfirm,
  Select,
  Upload,
} from 'antd';
import React, { useEffect, useRef, useState } from 'react';

interface ProductItem {
  productId: string;
  productName: string;
  serNum: number;
  hotFlag: string;
  picUrl: string;
  productSimDesc: string;
  productContentBind: string;
  categoryId: string;
  categoryName: string;
  childCategoryId?: string;
}

const { Option } = Select;

const ProductPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [currentProduct, setCurrentProduct] = useState<ProductItem | null>(
    null,
  );
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState('');
  const [editorContent, setEditorContent] = useState('');
  const [categories, setCategories] = useState<
    { categoryId: string; categoryName: string }[]
  >([]);
  const [childCategories, setChildCategories] = useState<
    { categoryId: string; categoryName: string }[]
  >([]);

  useEffect(() => {
    const fetchCategories = async () => {
      const data = await qryMainCategoryList();
      setCategories(data);
    };
    fetchCategories();
  }, []);

  // 父类目变化时获取子类目
  const handleParentCategoryChange = async (categoryId: string) => {
    if (categoryId) {
      try {
        const detail = await qryMainCategoryDetail({ categoryId });
        setChildCategories(detail.childCategoryList || []);
        // 清空子类目选择
        form.setFieldValue('childCategoryId', undefined);
      } catch (error) {
        message.error('获取子类目失败');
        setChildCategories([]);
      }
    } else {
      setChildCategories([]);
      form.setFieldValue('childCategoryId', undefined);
    }
  };

  // 将handleEdit和handleDelete移到columns定义之前
  const handleEdit = async (productId: string) => {
    try {
      const detail = await qryProductInfoDetail({ productId });
      setCurrentProduct(detail);
      setImageUrl(detail.picUrl || '');
      setEditorContent(detail.productContentBind || '');

      // 如果有父类目，获取子类目列表
      if (detail.categoryId) {
        try {
          const categoryDetail = await qryMainCategoryDetail({
            categoryId: detail.categoryId,
          });
          setChildCategories(categoryDetail.childCategoryList || []);
        } catch (error) {
          console.error('获取子类目失败:', error);
          setChildCategories([]);
        }
      }

      form.setFieldsValue({
        ...detail,
        hotFlag: detail.hotFlag || '0',
      });
      setModalVisible(true);
    } catch (error) {
      message.error('获取详情失败');
    }
  };

  const handleDelete = async (productId: string) => {
    try {
      await deleteProductInfo({ productId });
      message.success('删除成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const columns: ProColumns<ProductItem>[] = [
    {
      title: '排序序号',
      dataIndex: 'serNum',
      key: 'serNum',
      hideInSearch: true,
      width: 80,
    },
    {
      title: '产品编号',
      dataIndex: 'productId',
      key: 'productId',
      hideInSearch: true,
      width: 200,
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      key: 'productName',
    },
    {
      title: '父类目名称',
      dataIndex: 'categoryName',
      key: 'categoryName',
      hideInSearch: true,
      width: 150,
    },
    {
      title: '是否热门',
      dataIndex: 'hotFlag',
      key: 'hotFlag',
      width: 120,
      hideInSearch: true,
      render: (text) => (text === '1' ? '是' : '否'),
    },
    {
      title: '产品图片',
      dataIndex: 'picUrl',
      key: 'picUrl',
      width: 150,
      hideInSearch: true,
      render: (text: any) =>
        text ? (
          <img
            src={text}
            alt="产品图片"
            style={{ width: '80px', height: '45px', objectFit: 'cover' }}
          />
        ) : null,
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      valueType: 'option',
      render: (_, record) => [
        <Button
          key="edit"
          type="link"
          onClick={() => handleEdit(record.productId)}
        >
          编辑
        </Button>,
        <Popconfirm
          key="delete"
          title="确定要删除这个产品吗?"
          onConfirm={() => handleDelete(record.productId)}
          okText="确定"
          cancelText="取消"
        >
          <Button type="link" danger>
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  const handleAdd = () => {
    form.resetFields();
    setEditorContent('');
    setImageUrl('');
    setCurrentProduct(null);
    setChildCategories([]); // 清空子类目列表
    setModalVisible(true);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setConfirmLoading(true);

      const submitData = {
        ...values,
        picUrl: imageUrl || values.picUrl,
        productContentBind: editorContent,
      };

      if (currentProduct) {
        await updateProductInfo({
          ...submitData,
          productId: currentProduct.productId,
        });
        message.success('更新成功');
      } else {
        await addProductInfo(submitData);
        message.success('新增成功');
      }

      setModalVisible(false);
      actionRef.current?.reload();
    } catch (error) {
      message.error('操作失败');
    } finally {
      setConfirmLoading(false);
    }
  };

  const uploadProps: any = {
    // @ts-ignore
    customRequest: async ({ file, onSuccess, onError }) => {
      try {
        const response = await uploadMinio(file as File);
        if (response.data?.fileUrl) {
          setImageUrl(response.data.fileUrl);
          form.setFieldsValue({
            picUrl: response.data.fileUrl,
          });
          onSuccess?.(response, new XMLHttpRequest());
        } else {
          onError?.(new Error('上传失败'), new XMLHttpRequest());
        }
      } catch (error) {
        onError?.(error as Error, new XMLHttpRequest());
      }
    },
  };

  return (
    <PageContainer>
      <ProTable<ProductItem>
        actionRef={actionRef}
        rowKey="productId"
        columns={columns}
        request={async (params) => {
          const { current, pageSize, ...rest } = params;
          const result = await qryProductListPage({
            pageIndex: current,
            pageSize,
            param: rest,
          });
          return {
            data: result.list,
            total: result.total,
            success: true,
          };
        }}
        toolBarRender={() => [
          <Button
            key="add"
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            新增产品
          </Button>,
        ]}
      />

      <Modal
        title={currentProduct ? '编辑产品' : '新增产品'}
        open={modalVisible}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisible(false)}
        width={800}
      >
        <Form form={form} layout="vertical">
          {currentProduct && (
            <Form.Item name="productId" label="产品编号" hidden>
              <Input disabled />
            </Form.Item>
          )}
          <Form.Item
            name="productName"
            label="产品名称"
            rules={[{ required: true, message: '请输入产品名称' }]}
          >
            <Input placeholder="请输入产品名称" />
          </Form.Item>

          <Form.Item
            name="categoryId"
            label="产品父类目"
            rules={[{ required: true, message: '请选择产品父类目' }]}
          >
            <Select
              placeholder="请选择产品父类目"
              onChange={handleParentCategoryChange}
            >
              {categories.map((item) => (
                <Option key={item.categoryId} value={item.categoryId}>
                  {item.categoryName}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item name="childCategoryId" label="产品子类目">
            <Select
              placeholder="请选择产品子类目"
              disabled={childCategories.length === 0}
            >
              {childCategories.map((item) => (
                <Option key={item.categoryId} value={item.categoryId}>
                  {item.categoryName}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item name="serNum" label="排序序号">
            <InputNumber min={1} style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item name="hotFlag" label="是否热门">
            <Select>
              <Option value="0">否</Option>
              <Option value="1">是</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="picUrl"
            label="产品图片URL"
            rules={[{ required: true, message: '请上传产品图片' }]}
          >
            <Input disabled />
          </Form.Item>

          <Form.Item label="上传图片">
            <Upload {...uploadProps}>
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                }}
              >
                {imageUrl ? (
                  <img
                    src={imageUrl}
                    alt="产品图片"
                    style={{
                      width: '100%',
                      maxHeight: '200px',
                      marginBottom: '8px',
                    }}
                  />
                ) : null}
                <Button icon={<UploadOutlined />}>点击上传图片</Button>
              </div>
            </Upload>
          </Form.Item>

          <Form.Item name="productSimDesc" label="产品简介">
            <Input.TextArea rows={3} />
          </Form.Item>

          <Form.Item name="productContentBind" label="产品详情">
            <RichTextEditor
              value={editorContent}
              onChange={(content, html) => {
                setEditorContent(content);
                form.setFieldsValue({ productContentBind: html });
              }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default ProductPage;
